//
//  MessageNotifyCenter.m
//  jungoo
//
//  Created by VMODEV on 10/1/12.
//
//

#import "MessageNotifyCenter.h"
#import "ChatMessageViewController.h"
#import "MessageViewController.h"
#import "JGoAPI.h"

static MessageNotifyCenter *sharedMessageNotify = nil;

@interface MessageNotifyCenter()

- (void)attatchForceground;
- (void)attatchBackground;

@end

@implementation MessageNotifyCenter

@synthesize delegate = _delegate;

+ (MessageNotifyCenter*)sharedMessageNotify
{
    if (sharedMessageNotify == nil) {
        sharedMessageNotify = [MessageNotifyCenter new];
        [sharedMessageNotify attatchBackground];
        [sharedMessageNotify attatchForceground];
    }
    
    return sharedMessageNotify;
}

- (void)setDelegate:(id)receiver
{
    @synchronized(self) {
        _delegate = receiver;
    }
}

- (id)delegate
{
    @synchronized(self) {
        return _delegate;
    }
}

- (void)test:(NSDictionary*)countDictionary
{
   [JGoUtility showAlert:[NSString stringWithFormat:@"You have %d new messages",[[countDictionary objectForKey:@"num_messages"] integerValue]]];
}

- (void)attatchBackground
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    
    dispatch_async(queue, ^{                
        
        NSDictionary *user = [JGoUtility sharedCreateAccount];
        NSString *userId = [user objectForKey:@"user_id"];
        NSString *lastDate = [JGoUtility stringFromDate6:[NSDate date]];
        NSDictionary *countDictionary = nil;
        NSError *error = nil;
        
        countDictionary = [JGoAPI countMessagesWithUserId:userId activeConversationId:@"" fromDate:lastDate error:&error];
        
        if (!error) {
            lastDate = [[countDictionary objectForKey:@"server_time"] retain];
            NSInteger fcount = [[countDictionary objectForKey:@"num_messages"] integerValue];
            
            if (fcount > 0) {
                 [self performSelectorOnMainThread:@selector(alertNotify) withObject:nil waitUntilDone:YES];
            }
        }
        else {
            
        }
        
        while (YES) {
            
            NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
            
            if (self.delegate == nil) {
                
                error = nil;
                NSInteger count = -1;
                
                
                countDictionary = [JGoAPI countMessagesWithUserId:userId activeConversationId:@"" fromDate:lastDate error:&error];
                
                if (error) {
                    sleep(5);
                    continue;
                }
                
                count = [[countDictionary objectForKey:@"num_messages"] integerValue];
                
                if (count > 0) {
                    
                    [lastDate release];
                    lastDate = [[countDictionary objectForKey:@"server_time"] retain];
                    /*
                    NSArray *conversations = [JGoAPI getConversationsWithUserId:userId onlyOwner:NO error:&error];                    
                    
                    if (error) {
                        sleep(5);
                        continue;
                    }                                        
                    
                    for (NSDictionary* aConversation in conversations) {
                        
                        NSString *cId = [aConversation objectForKey:@"id"];
                        
                        NSArray *messages = [JGoAPI getMessagesWithUserId:userId
                                                           conversationId:cId
                                                                 fromDate:lastDate
                                                                   toDate:@"" error:&error];
                        
                        if ([messages count]) {
                            [self performSelectorOnMainThread:@selector(alertNotify:) withObject:[messages lastObject] waitUntilDone:YES];
                            break;
                        }
                        
                        sleep(0.5);
                    }                                        
                                                             
                    sleep(5);
                    */
                    
                    [self performSelectorOnMainThread:@selector(alertNotify) withObject:nil waitUntilDone:YES];                                         
                }
                else {
                    sleep(5);
                }                                 
            }
            else {                
                sleep(1);
            }
            
            [pool release];
        }
    });
    
}

- (void)attatchForceground
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    
    dispatch_async(queue, ^{
        
        NSDictionary *user = [JGoUtility sharedCreateAccount];
        NSString *userId = [user objectForKey:@"user_id"];
        
        while (YES) {
            
            NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
            
            if (self.delegate != nil &&
                [[[self.delegate class] description] isEqualToString:@"ChatMessageViewController"]) {
                
                NSError *error = nil;
                NSString *cId = [self.delegate activeIdentifier];
                NSArray *messages = [JGoAPI getMessagesWithUserId:userId
                                                   conversationId:cId
                                                         fromDate:@""
                                                           toDate:@"" error:&error];
                if (!error) {
                    messages = (id)[[messages reverseObjectEnumerator] allObjects];
                    
                    if ([self.delegate respondsToSelector:@selector(messageNotifyCenter:lastMessages:)]) {
                        [self.delegate messageNotifyCenter:self lastMessages:messages];
                    }
                }
                
                sleep(3);
            }
            else {
                sleep(10);
            }
            
            [pool release];
        }
    });
}

- (void)alertNotify
{
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle: @"Alumnee"
                                                         message: @"You have a new message!"
                                                        delegate: (id)self
                                               cancelButtonTitle: @"Cancel"
                                               otherButtonTitles: @"Go to Message",nil] autorelease];
    
    [alertView show];
    
}

- (void)alertNotify:(NSDictionary*)aMessage
{
    NSDictionary *aSender = [aMessage objectForKey:@"sender"];
    NSString *message = [NSString stringWithFormat:@"[%@]: %@",[aSender objectForKey:@"name"],[aMessage objectForKey:@"content"]];
    
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle: @"New Message"
                                                         message: message
                                                        delegate: (id)self
                                               cancelButtonTitle: @"Cancel"
                                               otherButtonTitles: @"View",nil] autorelease];
    
    alertView.tag = (NSInteger)[aMessage retain];
    
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    /*
    NSDictionary *aMessage = (id)[alertView tag];
    */
    
    if (buttonIndex == 1) {
        /*
        ChatMessageViewController *messageVC = [[[ChatMessageViewController alloc] initWithNibName:@"ChatMessageViewController"
                                                                                    bundle:nil] autorelease];
        UINavigationController *navc = [[[UINavigationController alloc] initWithRootViewController:messageVC] autorelease];
        
        messageVC.conversionId = [aMessage objectForKey:@"cid"];
        navc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        [[JGoUtility sharedRootViewController] presentModalViewController:navc animated:YES];
         */
        
        MessageViewController *messageVC = [[[MessageViewController alloc] initWithNibName:@"MessageViewController"
                                                                                            bundle:nil] autorelease];
        UINavigationController *navc = [[[UINavigationController alloc] initWithRootViewController:messageVC] autorelease];        
        navc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        [[JGoUtility sharedRootViewController] presentModalViewController:navc animated:YES];
    }
    
    /*
      [aMessage release];
    */
}

@end
